package com.jae.service.impl;

import com.jae.mapper.UserMapper;
import com.jae.model.ServiceRuntimeException;
import com.jae.model.Token;
import com.jae.model.user.User;
import com.jae.service.UserService;
import com.jae.utils.Assert;
import com.jae.utils.PasswordUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl  extends BaseServiceImpl implements UserService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserMapper userMapper;

    //鉴权服务器，这个一般放在数据库的系统参数去
    @Value("${authentication.server.admin}")
    private String authentication_server_admin;

    /**
     *
     * @param username  用户名
     * @param password  密码
     * @param clientType    客户端-client
     * @return
     */
    @Override
    public Token login(String username, String password,String clientType) {
        Assert.hasText(username,"用户名不能为空");
        Assert.hasText(password,"密码不能为空");
        Map userMap = new HashMap();
        userMap.put("username",username);
        userMap.put("is_deleted",-1);
        User user = userMapper.findByUsername(userMap);
        Assert.notNull(user,"用户名不存在");

        if(!PasswordUtils.matches(password,user.getPassword()))
            serviceError("密码错误");

        String url = authentication_server_admin +"/oauth/token?username="
                +username+"&password="+password+"&grant_type=password&client_id="+clientType+"-client&client_secret="+clientType;
        try {
            MultiValueMap map = new LinkedMultiValueMap();
            map.add("username", username);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,map, String.class);
            String result = responseEntity.getBody();
            log.debug("结果"+result);
            if(result.contains("error")){
                throw new ServiceRuntimeException("密码错误");
            }else{
                Token token = (Token) JSONObject.toBean(JSONObject.fromObject(result),Token.class);
                return token;
            }
        } catch (RestClientException e) {
            throw new ServiceRuntimeException("密码错误");
        }
    }

    @Override
    public boolean regist(String username, String password) {
        log.debug(username);
        Assert.hasText(username,"用户名不能为空");
        Assert.hasText(password,"密码不能为空");
        Map map = new HashMap();
        map.put("username",username);
        if(userMapper.findByUsername(map) != null)
            serviceError("用户名已存在");

        User user = new User();
        user.setUsername(username);
        user.setPassword(PasswordUtils.encode(password));
        user.setCreated_time(new Date());
        if(userMapper.insert(user) != 1)
            serviceError("新增用户失败");

        return true;
    }

    @Override
    public boolean insert(User user) {
        return false;
    }

    @Override
    public void logout(User user) {
        userMapper.deleteRefreshTokenByUsername(user.getUsername());
        userMapper.deleteAccessTokenByUsername(user.getUsername());
    }
}
